﻿IF EXISTS (
    SELECT
      1
    FROM sysobjects
    WHERE id = OBJECT_ID('bd_proc_schedule_employee')
      AND type IN ('P', 'PC')
  )
  DROP PROCEDURE bd_proc_schedule_employee

GO

-- =============================================
-- Author:      YFC
-- Create date: 2020-07-17 22:43:43
-- Database:    [scm_main-hysj2]
-- Description: 排班管理-班组员工保存
-- =============================================

CREATE PROCEDURE bd_proc_schedule_employee
(
  @employeeJson VARCHAR(MAX)
)
AS
BEGIN
  SET NOCOUNT ON;

  SELECT *
  INTO #data
  FROM OPENJSON(@employeeJson)
  WITH (
  groupId INT,
  userSerial BIGINT
  )

  DECLARE @groupId INT

  SELECT TOP 1 @groupId = groupId FROM #data 

  BEGIN TRY
    BEGIN TRANSACTION

      MERGE
      INTO bd_schedule_group_employee p
      USING #data s ON p.group_id = s.groupId
        AND p.user_serial = s.userSerial
      WHEN NOT MATCHED BY TARGET
        THEN INSERT(group_id, user_serial)
            VALUES(groupId, userSerial)
      WHEN NOT MATCHED BY SOURCE AND p.group_id = @groupId
        THEN DELETE;
      ;

    COMMIT TRANSACTION
  END TRY
  BEGIN CATCH
    DECLARE @errStr VARCHAR(MAX) = ERROR_MESSAGE();

    IF XACT_STATE() <> 0
    BEGIN
      ROLLBACK TRANSACTION;
    END;
    RAISERROR (@errStr, 16, 1);
  END CATCH;

  DROP TABLE #data;

  SET NOCOUNT OFF;
END
GO
